<template>
  <div class="alarm-rule-list-container">
    <header-search-form
      :searchFormData="searchForm"
      @search="search"
    />
    <lan-table
      size="small"
      :config="dataTable"
      :tableData="tableData"
      @search="search"
    >
      <template #type="scope">
        <el-input v-model="scope.row.type"></el-input>
      </template>
    </lan-table>
    <edit
      ref="editComponent"
      @refresh="search"
    ></edit>
  </div>
</template>

<script>
import Edit from './edit';
import HeaderSearchForm from './headerSearchForm.vue';
import lanTable from '../../../components/lanTable';
import { getActiveDisplay, getActiveColor } from './servers';
import * as moment from 'moment';
import { Message, MessageBox } from 'element-ui';
import { SortType, MomentFormat } from '../../../constants/common';
import { parseError } from '../../../utils';
import { getAlarmRuleListApi, deleteAlarmRuleApi } from '../../../api/alarmRule';
let refresh = false;

export default {
  components: {
    lanTable,
    Edit,
    HeaderSearchForm
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'alarmRuleCreate' || from.name === 'alarmRuleEdit') refresh = true;
    next();
  },
  data() {
    return {
      dataTable: {
        pageSize: 10,
        totalCount: 0,
        currentPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
        sort: {
          orderBy: 'createdAt',
          sortType: SortType.DESC
        },
        columnList: [
          {
            name: 'index',
            label: '',
            type: 'index'
          },
          {
            name: 'name',
            label: '报警规则名称'
          },
          {
            name: 'parameterName',
            label: '设备参数'
          },
          {
            name: 'alertThreshold',
            label: '预警阈值'
          },
          {
            name: 'alarmThreshold',
            label: '报警阈值'
          },
          {
            label: '是否可用',
            type: 'formatter',
            name: 'active',
            scope: true,
            width: '100px',
            formatter: getActiveDisplay,
            style: {
              color: getActiveColor
            }
          },
          {
            name: 'createdAt',
            label: '创建时间',
            sortable: true
          },
          {
            name: 'updatedAt',
            label: '更新时间'
          },
          {
            type: 'button',
            label: '操作',
            buttons: [
              {
                isShow: () => this.userGuardList.includes(this.guard.AlarmRuleManage),
                type: 'text',
                text: '编辑',
                size: 'small',
                method: row => {
                  this.showEdit(row.uuid);
                }
              },
              {
                isShow: () => this.userGuardList.includes(this.guard.AlarmRuleManage),
                type: 'text',
                text: '删除',
                size: 'small',
                method: row => {
                  this.remove(row.uuid, row.name);
                }
              }
            ]
          }
        ]
      },
      searchForm: {
        btnLoading: false,
        name: ''
      },

      tableData: [],
      currentPage: 1,
      pageSize: 10,
      pageSizes: [5, 10, 20, 50, 100],
      totalCount: 0
    };
  },
  created() {
    this.search();
  },
  methods: {
    getActiveDisplay,
    getActiveColor,
    showEdit(uuid) {
      this.$refs.editComponent.showDialog(uuid);
    },
    remove(uuid, name) {
      MessageBox.confirm(`确认删除报警规则${name}吗？`, '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        deleteAlarmRuleApi(uuid)
          .then(() => Message.success('删除报警规则成功'))
          .catch(error => Message.error(parseError(error)))
          .finally(() => this.search());
      });
    },
    search() {
      this.searchForm.btnLoading = true;
      getAlarmRuleListApi(this.dataTable.currentPage - 1, this.dataTable.pageSize, this.dataTable.sort.sortType, this.searchForm.name)
        .then(({ total_count, data }) => {
          this.dataTable.totalCount = total_count;
          this.tableData = data.map(alarmRule => {
            return {
              uuid: alarmRule.uuid,
              name: alarmRule.name,
              parameterName: alarmRule.parameter_name,
              alertThreshold: alarmRule.alert_threshold,
              alarmThreshold: alarmRule.alarm_threshold,
              active: alarmRule.active,
              alarmTypeList: alarmRule.alarm_type_list,
              deviceTypeList: alarmRule.device_type_list,
              recipientList: alarmRule.recipient_list,
              createdAt: moment(alarmRule.created_at).format(MomentFormat),
              updatedAt: moment(alarmRule.updated_at).format(MomentFormat)
            };
          });
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.searchForm.btnLoading = false));
    },
    pageSizeChangeHandler() {
      this.currentPage = 1;
      this.search();
    },
    currentPageChangeHandler() {
      this.search();
    }
  }
};
</script>

<style lang="scss">
.alarm-rule-list-container {
  padding: 10px;
}
</style>
